package com.lagou.edu.service.impl;

import com.lagou.edu.dao.LagouAuthCodeDao;
import com.lagou.pojo.LagouAuthCode;
import com.lagou.service.LagouAuthCodeService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author caiwei
 * @date 2020-11-18 23:20
 */
@Service
public class LagouAuthCodeServiceImpl implements LagouAuthCodeService {


    @Autowired
    private LagouAuthCodeDao lagouAuthCodeDao;

    @Value("${config.code.validate.expire}")
    private int codeExpireSeconds;

    @Override
    public void createAuthCode(String email, String code) {

        long createTime = System.currentTimeMillis();
        long expireTime = createTime + codeExpireSeconds * 1000 * 60;

        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCode(code);
        lagouAuthCode.setCreatetime(new Date(createTime));
        lagouAuthCode.setExpiretime(new Date(expireTime));

        lagouAuthCodeDao.save(lagouAuthCode);

    }

    @Override
    public int validateAuthCode(String email, String code) {
        LagouAuthCode latest = lagouAuthCodeDao.findFirstByEmailOrderByIdDesc(email);
        //0 注册成功 1 该邮箱已注册 2 注册码已过期 3 请求服务超时，熔断 4 验证码错误 5 该邮箱没有发送验证码
        if (latest == null){
            return 5;
        }
        if (!latest.getCode().equalsIgnoreCase(code)){
            return 4;
        }

        long expireTime = latest.getExpiretime().getTime();
        if (expireTime <= System.currentTimeMillis()){
            return 2;
        }
        return 0;
    }

    @Override
    public boolean validateOneSendCode(String email) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,-1);
        Date createTime = calendar.getTime();
        System.out.println(sdf.format(createTime));
        LagouAuthCode firstByEmailAndCreatetimeBetween = lagouAuthCodeDao.findFirstByEmailAndCreatetimeAfter(email, createTime);
        if(firstByEmailAndCreatetimeBetween==null){
            return true;
        }
        System.out.println("存在一分钟内发送过验证码信息！");
        return false;
    }
}
